from rest_framework.viewsets import GenericViewSet,ViewSet
from rest_framework import mixins
from . import models,serializers
from django.conf import settings
from django.core.cache import cache
from rest_framework.response import Response
class BannerViewSet(GenericViewSet,mixins.ListModelMixin):
    queryset = models.Banner.objects.filter(is_delete=False,is_show=True).order_by('-orders').all()[:settings.BANNER_COUNT]
    serializer_class = serializers.BannerSerializer

    # 要建立接口缓存，接口的请求逻辑必须自己实现
    # 有缓存走缓存，没用缓存走数据库，同步给缓存
    def list(self, request, *args, **kwargs):
        banner_list = cache.get('banner_list')
        # 如果没有缓存
        if not banner_list:
            print('走了数据库')
            response = super().list(request,*args,**kwargs)
            banner_list = response.data
            # 设立一天的缓存，如果一天内想主动更新，如何操作？
            cache.set('banner_list',banner_list,86400)
        return Response(banner_list)